package org.whb.basic.interceptor;

import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //从请求头中获取到token
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)){ //请求头中有token

            Object logininfo = redisTemplate.opsForValue().get(token);
            if (logininfo!=null){ //logininfo没有过期，重设过期时间，放行
                redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
                return true;
            }

        }
        //没有token，或者设置的token已经过期，返回错误信息，并且拦截
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;

        /*if (StringUtils.isEmpty(token)){ //请求头中没有token
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noLogin\"}");
            writer.flush();
            writer.close();
            return false;
        }
        Object logininfo = redisTemplate.opsForValue().get(token);
        if (logininfo==null){ //redis中存储的logininfo已过期
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"message\":\"noLogin\"}");
            writer.flush();
            writer.close();
            return false;
        }
        //请求中有token而且logininfo没有过期，重设过期时间，放行
        redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);

        return true;*/
    }

}
